<?php
	include_once "../include/Functions.php";
	
	$code = $_GET["code"];
	$person_id = $_GET["state"];
	//echo $code;
	
	//open connection
	$ch = curl_init();

	//set the url, number of POST vars, POST data
	curl_setopt($ch,CURLOPT_URL, "https://www.strava.com/oauth/token");
	curl_setopt($ch,CURLOPT_POST, true);
	curl_setopt($ch,CURLOPT_POSTFIELDS, "client_id=3028&client_secret=e9918f1f0747b9cb0382b815b496dbb11bb45510&code={$code}");
	curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	
	//execute post
	$result = curl_exec($ch);
	
	if ($result === FALSE) 
		echo "Curl Failed: " . curl_error($ch);
	
	$strava= json_decode($result, true);

	//close connection
	curl_close($ch);	
	
	$sql = "UPDATE person 
			SET strava_token = '{$strava['access_token']}',
			strava_token_type = '{$strava['token_type']}',
			strava_id = '{$strava['athlete']['id']}',
			strava_export = true
			WHERE id = {$person_id}";
	//echo $sql;
	
	Functions::execSql($sql);
	
	echo "<script>location.href='../index.php?page=pages/configuration.php'</script>";
?>